package apis

import (
	"first-gin/common"
	"first-gin/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

type UserController struct {
}

// GetUserInfo 获取用户信息
//(u UserController) 表明  这是  apis 包下 的 UserController 的 xx方法

func (u UserController) GetUserInfo(routerServer *gin.Context) {
	idStr := routerServer.Param("id")
	id, _ := strconv.Atoi(idStr)
	user, _ := models.GetUserTest(id)
	common.ReturnSuccess(routerServer, "user info", user)
}

func (u UserController) AddUser(routerServer *gin.Context) {
	name := routerServer.DefaultPostForm("name", "default")
	id, err := models.AddUser(name)
	if err != nil {
		common.ReturnError(routerServer, "add user failed"+err.Error())
	} else {
		common.ReturnSuccess(routerServer, "add user success", id)
	}
}

func (u UserController) UpdateByUserId(routerServer *gin.Context) {
	name := routerServer.DefaultPostForm("name", "default")
	idStr := routerServer.DefaultPostForm("id", "999")
	id, _ := strconv.Atoi(idStr)
	user := models.User{Id: id, Name: name}
	err := models.UpdateUser(user)
	if err != nil {
		common.ReturnError(routerServer, "update user failed"+err.Error())
	} else {
		common.ReturnSuccess(routerServer, "update user success", nil)
	}
}
func (u UserController) DeletedById(routerServer *gin.Context) {
	idStr := routerServer.Param("id")
	id, _ := strconv.Atoi(idStr)
	err := models.DeletedById(id)
	if err != nil {
		common.ReturnError(routerServer, "delete user failed"+err.Error())
	} else {
		common.ReturnSuccess(routerServer, "delete user success", nil)
	}

}

// GetList 获取用户列表
func (u UserController) GetList(routerServer *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
		}
	}()
	num1 := 1
	num2 := 0
	num3 := num1 / num2
	common.ReturnError(routerServer, "no user exist"+string(rune(num3)))
}
